package cn.com.user.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;



@Controller
@RequestMapping("/wechat/init")
public class WechatInitController {
	
	@RequestMapping(method = { RequestMethod.GET })  
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("微信接入");
		
		//设置字符集
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		//获取输出
		PrintWriter out = resp.getWriter();
			
		//接入 调用方法 处理接入
		//接收参数
				String signature = req.getParameter("signature");
				String timestamp = req.getParameter("timestamp");
				String nonce = req.getParameter("nonce");
				String echostr = req.getParameter("echostr");
					
				//校验
				List<String> list = new ArrayList<String>();
				list.add("cit");
				list.add(timestamp);
				list.add(nonce);
				//排序
				Collections.sort(list);
				//拼接字符串---》shal加密
				StringBuffer buffer = new StringBuffer();
				for(String string : list){
					buffer.append(string);
				}
				//使用apache commons codec	
				String shalstr = DigestUtils.shaHex(buffer.toString());
				//对比
				boolean flag = shalstr.equals(signature);
				if(flag){
					System.out.println("恭喜接入成功");
					out.print(echostr);
					out.flush();
				}
	}


}
